package com.dove.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dove.common.Constants;
import com.dove.common.exception.ServiceException;
import com.dove.controller.Dto.UserDto;
import com.dove.entity.Menu;
import com.dove.mapper.RoleMapper;
import com.dove.mapper.RoleMenuMapper;
import com.dove.mapper.UserMapper;
import com.dove.entity.User;
import com.dove.service.IMenuService;
import com.dove.service.IUserService;
import com.dove.utils.TokenUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private IMenuService menuService;

    @Override
    public IPage<User> getPage(Integer current, Integer size) {
        IPage<User> page = new Page<>(current, size);
        return userMapper.selectPage(page, null);
    }

    @Override
    public IPage<User> getPage(Integer current, Integer size, User user) {
        IPage<User> page = new Page<>(current, size);
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
//        lqw.like(Strings.isNotEmpty(user.getId().toString()),User::getId, user.getId());
        lqw.like(Strings.isNotEmpty(user.getUsername()), User::getUsername, user.getUsername());
        lqw.like(Strings.isNotEmpty(user.getNickname()), User::getNickname, user.getNickname());
        lqw.like(Strings.isNotEmpty(user.getEmail()), User::getEmail, user.getEmail());
        lqw.like(Strings.isNotEmpty(user.getPhone()), User::getPhone, user.getPhone());
        lqw.like(Strings.isNotEmpty(user.getAddress()), User::getAddress, user.getAddress());
        return userMapper.selectPage(page, lqw);
    }

    @Override
    public UserDto login(UserDto userDto) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq(Strings.isNotBlank(userDto.getUsername()), "username", userDto.getUsername());
        qw.eq(Strings.isNotBlank(userDto.getPassword()), "password", userDto.getPassword());
        User dbUser;
        try {
            dbUser = userMapper.selectOne(qw);
        } catch (Exception e) {//期望一个结果多个
            e.printStackTrace();
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        if (dbUser != null) {//登录验证通过
            BeanUtils.copyProperties(dbUser, userDto);
            //设置token
            String token = TokenUtils.getToken(dbUser.getId().toString(), dbUser.getPassword());
            userDto.setToken(token);

            //查询权限菜单
            String role = dbUser.getRole();//ROLE_
            Integer roleId = roleMapper.selectByTag(role);

            //设置用户菜单列表
            List<Menu> roleMenus = getRoleMenus(roleId);
            userDto.setMenus(roleMenus);
            return userDto;
        } else {
            throw new ServiceException(Constants.CODE_600, "账户或密码错误");
        }
    }

    @Override
    public Boolean register(UserDto userDto) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq(Strings.isNotBlank(userDto.getUsername()), "username", userDto.getUsername());
        //qw.eq(Strings.isNotBlank(userDto.getPassword()),"password",userDto.getPassword());
        User dbUsers = userMapper.selectOne(qw);
        User user;
        if (dbUsers == null) {//账户可用
            user = new User();
            BeanUtils.copyProperties(userDto, user);
            return userMapper.insertUser(user) > 0;
        } else {
            throw new ServiceException(Constants.CODE_700, "注册账号已存在");
        }
    }

    @Override
    public Page<User> myFindPage(Page<User> page, String username, String nickname, String address) {
        return userMapper.myFindPage(page,username,nickname,address);
    }

    /**
     * 获取用户菜单列表
     * @param roleId
     * @return
     */
    private List<Menu> getRoleMenus(Integer roleId){
        //当前角色所有菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectByroleId(roleId);
        //查出系统所有菜单
        List<Menu> menus = menuService.findMenus("");
        //new一个最后筛选完成后的list
        List<Menu> roleMenus = new ArrayList<>();
        //筛选当前用户的菜单
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())) {
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            //移除children中不在menusIds集合中的元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        return roleMenus;
    }
}
